# -*- coding: utf8 -*-

from subprocess import Popen, PIPE
from archive import BaseAdapter, which


class PDFArchive(BaseAdapter):

    bin = None

    proc = None

    max_scale_width = 1200
    max_scale_height = 1920

    stop = False

    def get_files( self ):

        self.bin = which("pdfinfo")

        names = []

        self.proc = Popen([
            self.bin,
            self.file_name
        ], stdout=PIPE)
        self.proc.wait()

        n_pages = 0
        for line in self.proc.stdout.readlines():
            line = line.strip().lower().decode("utf-8")
            if line.startswith("pages:"):
                line = line.replace("pages:", "").strip()
                n_pages = int(line)
                break

        for i in range(n_pages):
            names.append("%d.png" % i)

        return names

    def terminate(self):
        if self.proc and self.proc.poll() is None:
            self.proc.terminate()
        return

    def extract_files( self, into_dir):

        self.bin = which("convert")

        self.proc = Popen([
            self.bin,
            "-density", "300x300",
            self.file_name,
            "-resize", "%sx" % self.max_scale_width,
            "%s/%%d.png" % into_dir
        ], stdout=PIPE)
        self.proc.wait()

        return self.proc.poll() == 0
